<?php
class CategoryFilter extends AbstractFilter {

	public $category;
	
	protected $_criteria = null;
	
	public function init($criteria) {
		$this->_criteria = $criteria;
		if (isset($_GET['cat'])) $this->category = $_GET['cat'];
	}
	
	public function apply() {
		if ($this->category) {
			$this->_criteria->addAndCondition("category_id=".$this->category, 'category');
		}
	}
	
	public function getClearUrl() {
		$gets = $_GET;
		unset($gets['cat']);
		return Yii::app()->createAbsoluteUrl('site/index', $gets);
	}
	
	public function isApplied() {
		return isset($_GET['cat']);
	}
	
	protected $_postCountData = null;
	
	protected function _getPostCount($catId) {
		if (!$this->_postCountData) {
			$c = clone $this->_criteria;
			$c->removeCondition('category');
			$c->group = 'category_id';
			$c->select = 'category_id, COUNT(p.id) as count';
			
			$cmd = $c->getCommand();
			$cmd->from = Post::model()->tableName().' AS p';
			$data = $cmd->queryAll();
			
			$this->_postCountData = array();
			foreach($data as $row) {
				$this->_postCountData[$row['category_id']] = $row['count'];
			}
		}
		return isset($this->_postCountData[$catId]) ? $this->_postCountData[$catId] : 0;
	}
	
	public function getItems($parentId=null) {
		$cmd = Yii::app()->db->createCommand();
		$cmd->from = Category::model()->tableName();
		$cmd->order = 'position';

		if ($parentId)
			$cmd->andWhere('parent_category_id='.$parentId);
		else
			$cmd->andWhere('parent_category_id is NULL');
		$data = $cmd->queryAll();
		foreach($data as &$row)
			$row['count'] = $this->_getPostCount($row['id']);
		return $data;
	}
	
	public function getItemUrl($item) {
		$gets = $_GET;
		$gets['cat'] = $item['id'];
		return Yii::app()->createAbsoluteUrl('site/index', $gets);
	}

	public function isSelected($item) {
		return isset($_GET['cat']) && $_GET['cat']==$item['id'];
	}

	public function getTemplate() {
		return '/catalog/filter/category';
	}
}